//
//  RegionView.swift
//  Box
//
//  Created by mn on 2025/4/1.
//
import UIKit
import SnapKit

class RegionView: UIView, UITableViewDelegate, UITableViewDataSource {

    private let provinceTableView = UITableView()
    private let cityTableView = UITableView()
    private let districtTableView = UITableView()
    var doneRegion:((String?,String?) -> Void)?

    var provinces = [RegionInfo]()
    lazy var close: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("关闭", for: .normal)
        button.setTitleColor(.fromHex("#222222"), for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 15)
        button.addAction {
            [weak self] in
            self?.removeFromSuperview()
        }
        return button
    }()
    lazy var done: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("完成", for: .normal)
        button.setTitleColor(.fromHex("#222222"), for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 15)
        button.addAction {
            [weak self] in
            self?.doneAction()
        }
        return button
    }()
    
    func doneAction() {
        let (a, b) = selectRegion()
        if b?.components(separatedBy: "@").count != 3 {
            findViewController()?.toast("请选择完整的省市区")
            return
        }
        doneRegion?(a, b)
        removeFromSuperview()
    }
    
    private var cities: [RegionInfo] = [] // 城市数据
    private var districts: [RegionInfo] = [] // 区县数据

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
    }

    private func setupViews() {
        var view : UIView? = nil
        backgroundColor = .white
        layer.cornerRadius = 19
        layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        addSubview(close)
        addSubview(done)
        let line = UIView()
        line.backgroundColor = .lightGray
        addSubview(line)
        
        close.snp.makeConstraints { make in
            make.left.top.equalToSuperview().offset(16)
        }
        done.snp.makeConstraints { make in
            make.right.top.equalToSuperview().inset(16)
        }
        line.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(16)
            make.height.equalTo(1)
            make.top.equalToSuperview().offset(49)
        }
        
        [provinceTableView,cityTableView,districtTableView].forEach { table in
            addSubview(table)
            table.delegate = self
            table.dataSource = self
            table.registerCell(UITableViewCell.self)
            table.separatorColor = .clear
            table.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(50)
                if let view{
                    make.left.equalTo(view.snp.right)
                }else{
                    make.left.equalToSuperview()
                }
                make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom)
                make.width.equalToSuperview().dividedBy(3)
            }
            view = table
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == provinceTableView {
            return provinces.count
        } else if tableView == cityTableView {
            return cities.count
        } else {
            return districts.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.cell(indexPath)
        cell.textLabel?.font = .systemFont(ofSize: 14)
        cell.textLabel?.textAlignment = .center
        if tableView == provinceTableView {
            cell.textLabel?.text = provinces[indexPath.row].name
        } else if tableView == cityTableView {
            cell.textLabel?.text = cities[indexPath.row].name
        } else {
            cell.textLabel?.text = districts[indexPath.row].name
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == provinceTableView {
            cities = provinces[indexPath.row].childrenList ?? []
            districts = []
            districtTableView.reloadData()
            cityTableView.reloadData()
        } else if tableView == cityTableView {
            districts = cities[indexPath.row].childrenList ?? []
            districtTableView.reloadData()
        }
    }
    
    func selectRegion() -> (String?,String?) {
        guard let provinceIndex = provinceTableView.indexPathForSelectedRow?.row else { return (nil,nil) }
        
        var selectedRegion = provinces[provinceIndex].name
        var code = provinces[provinceIndex].code
        
        if let cityIndex = cityTableView.indexPathForSelectedRow?.row {
            selectedRegion += "\(cities[cityIndex].name)"
            code += "@\(cities[cityIndex].code)"

            if let districtIndex = districtTableView.indexPathForSelectedRow?.row {
                selectedRegion += "\(districts[districtIndex].name)"
                code += "@\(districts[districtIndex].code)"
            }
        }
        return (selectedRegion,code)
    }
    
}
